//
//  DishView.m
//  XRmenu
//
//  Created by shengchao yang on 11-11-28.
//  Copyright 2011年 foxhis. All rights reserved.
//

#import "MainView.h"

#import "DishCatalogView.h"
#import "MainViewCell.h"
#import "DisplayModeView.h"
#import "XRMaskView.h"
#import "MaskView.h"
#import "MainViewSection.h"
#import "MyOrderView.h"

#define kTagOfStartMainView 5000
#define kTagOfTableViewSection  5200
#define kTagOfTableViewRow      5400

@interface MainView(Private) 
-(void) addNotification;
-(void) removeNotification;
-(void) initMainViewPluSort:(NSInteger) sortIndex;
-(void) SelectMainViewPluPlu;
-(void) MyOrderNumberChanged;
-(void) scrollToCurrentPluIndex;
@end

@implementation MainView

-(id) initWithStyle:(NSString *)stylename ViewName:(NSString *)vname
{
    self = [super initWithStyle:stylename ViewName:vname]; 
    [self addNotification];//注册主界面的所有通知消息
    if (self) {        
        //在界面上呈现tableview
        NSDictionary *tdict = [[[APPSESSION.allconfig objectForKey:@"UI Skin"] objectForKey:stylename] objectForKey:vname];
        NSDictionary *tabdict = [[[APPSESSION.allconfig objectForKey:@"UIKit CSS"] objectForKey:@"TableView CSS"] objectForKey:[tdict getStringValueAtPath:@"sub tableview/table view style"]];
        if (tdict) {
            [self setTableViewProperty:tabdict Frame:CGRectFromString([tdict getStringValueAtPath:@"sub tableview/table view rect"])];
        }
                
        //画出大类按钮的view
        DishCatalogView *clv=[[DishCatalogView alloc] initWithStyle:stylename ViewName:[NSString stringWithFormat:@"%@/Dish Catalog View",vname]];//把大类对象传进去用于显示大类的按钮
        clv.tag=kTagOfStartMainView;
        clv.delegate=self;
        [self addSubview:clv];
        [clv release];
        
        //画出显示模式外围的view
        DisplayModeView *dmv=[[DisplayModeView alloc] initWithStyle:stylename ViewName:[NSString stringWithFormat:@"%@/Display Mode View",vname]];
        dmv.tag=kTagOfStartMainView+1;
        [self addSubview:dmv];
        [dmv release];
        
        displayIndex=1;//默认大图浏览
        [dmv changeModeView:displayIndex];
        
        [self viewWithTag:kTagOfStartBT+5].hidden=YES;//向下的箭头默认隐藏
        [self MyOrderNumberChanged];//更新我的点单数字
        currentSectionIndex = APPSESSION.currentSortIndex;
        
        //在右上角显示大类的名称
        if ([self viewWithTag:kTagOfStartBT+3] && [APPSESSION.pluMenus count]>0) {
            UIButton *btn =(UIButton *) [self viewWithTag:kTagOfStartBT+3]; 
            [btn.titleLabel setFont:[UIFont fontWithName:@"Arial" size:20.0f]];
            [btn setTitleColor:RGBA(75, 42, 43, 254) forState:UIControlStateNormal];
            [btn setBackgroundImage:nil forState:UIControlStateNormal];
            [btn setTitle:JsonFiled(((PluMenu *)[APPSESSION.pluMenus objectAtIndex:APPSESSION.currentMenuIndex]).pmDescripts) forState:UIControlStateNormal];
        }
        
        APPSESSION.lastPluIndex=APPSESSION.currentPluIndex;
        [self scrollToCurrentPluIndex];
    }
    return self;
}
#pragma mark -
#pragma mark 大类和小类界面的初始化方法
//选中大类时主界面上发生的变化(只有在选中大类时被DishCatalogView里的委托调用)
-(void) DishCatalogUpdate:(NSInteger)newMenuIndex{
    DebugLog(@"选中大类的index=%d", newMenuIndex);
    [APPSESSION updateCurrentMenuIndex:newMenuIndex];//更新当前大类的下标
    
    //1.在右上角显示大类的名称
    if ([self viewWithTag:kTagOfStartBT+3] && [APPSESSION.pluMenus count]>0) {
        UIButton *btn =(UIButton *) [self viewWithTag:kTagOfStartBT+3]; 
        [btn.titleLabel setFont:[UIFont fontWithName:@"Arial" size:20.0f]];
        [btn setTitleColor:RGBA(75, 42, 43, 254) forState:UIControlStateNormal];
        [btn setBackgroundImage:nil forState:UIControlStateNormal];
        [btn setTitle:JsonFiled(((PluMenu *)[APPSESSION.pluMenus objectAtIndex:newMenuIndex]).pmDescripts) forState:UIControlStateNormal];
    }
    //2.条件判断(当大类下面的小类数据为空的时候，向下的箭头不显示)
    if ([APPSESSION.pluSorts count]==0) {
        [self viewWithTag:kTagOfStartBT+5].hidden=YES;
    }
    //3.重绘tableview
    currentSectionIndex = APPSESSION.currentSortIndex;
    [((UITableView *)[self viewWithTag:kTagOfStartTableView]) reloadData];    
    //4.更新显示模式界面里的数据
    postN(kMessage_DishplayModeView_UpdateData);
    //5.更新临时变量
    
    [self scrollToCurrentPluIndex];
}

//根据小类section的下标更新下面的菜品数组(只有在选中小类名称时调用!)
-(void) initMainViewPluSort:(NSInteger) newSortIndex{
    DebugLog(@"选中小类section=%d", newSortIndex);
    
    if (newSortIndex == currentSectionIndex) {
        currentSectionIndex=-1;
    }else{
        [APPSESSION updateCurrentSortIndex:newSortIndex];
        currentSectionIndex = newSortIndex;
    }    
    
    //1.更新tableview里的数据
    [((UITableView *)[self viewWithTag:kTagOfStartTableView]) reloadData];
    
    //2.更新显示模式界面里的数据
    postN(kMessage_DishplayModeView_UpdateData);
}

//在OnePicModeView里翻页时调用
-(void) SelectNextPluSort:(NSNotification *)note{
	NSDictionary *infos = [note userInfo];
	if ([infos objectForKey:@"newSortIndex"]) {
        NSInteger newSortIndex=[[infos objectForKey:@"newSortIndex"] intValue];
        DebugLog(@"newSortIndex=%d", newSortIndex);
        BOOL temp=YES;
        if (newSortIndex > APPSESSION.currentSortIndex) {
            temp=YES;
        }else{
            temp=NO;
        }
        
        [APPSESSION updateCurrentSortIndex:newSortIndex];
        
        //更新tableview里的数据
        currentSectionIndex = newSortIndex;
        [((UITableView *)[self viewWithTag:kTagOfStartTableView]) reloadData];
        
        if (temp) {
            APPSESSION.currentPluIndex=-1;
        }else{
            APPSESSION.currentPluIndex=[APPSESSION.pluPlus count];
        }
	}
}

#pragma mark -
#pragma mark 主窗口通知事件的注册与移除
-(void) addNotification{
    addNObserver(@selector(MyOrderNumberChanged), kMessage_MainView_MyOrderNumberChanged);
    addNObserver(@selector(SelectMainViewPluPlu), kMessage_MainView_SelectMainViewPluPlu);
    addNObserver(@selector(SelectNextPluSort:), kMessage_MainView_SelectNextPluSort);
}
-(void) removeNotification{
    removeNObserver(kMessage_MainView_MyOrderNumberChanged);
    removeNObserver(kMessage_MainView_SelectMainViewPluPlu);
    removeNObserver(kMessage_MainView_SelectNextPluSort);
}

#pragma mark -
#pragma mark 主窗口接收通知事件的处理方法
//修改我的点单数量
-(void) MyOrderNumberChanged{
    [APPSESSION getAllMyOrder];
    if ([self viewWithTag:kTagOfStartBT+4]) {
        UIButton *btn =(UIButton *) [self viewWithTag:kTagOfStartBT+4]; 
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageWithContentsOfFile:[XRmenuPublic getGeneralSkinImg:@"myorder_number.png"]] forState:UIControlStateNormal];
        [btn setTitle:[NSString stringWithFormat:@"%d",[APPSESSION.myOrders count]] forState:UIControlStateNormal];
    }
}

//设置菜品的选中状态(子view通过消息调用，MainView里直接调用)
-(void) SelectMainViewPluPlu{
    //判定是否需要去掉上一个row的选中状态
    if(APPSESSION.lastPluIndex != APPSESSION.currentPluIndex && [self viewWithTag:kTagOfTableViewRow + APPSESSION.lastPluIndex]){
        MainViewCell *cell=(MainViewCell *)[self viewWithTag:kTagOfTableViewRow + APPSESSION.lastPluIndex];
        [cell setSelectedRow:NO];
    }
    
    //设置只有当前菜品选中状态
    if([self viewWithTag:kTagOfTableViewRow + APPSESSION.currentPluIndex]){
        MainViewCell *cell=(MainViewCell *)[self viewWithTag:kTagOfTableViewRow + APPSESSION.currentPluIndex];
        [cell setSelectedRow:YES];
    }
    DebugLog(@"last=%d,current=%d", APPSESSION.lastPluIndex,APPSESSION.currentPluIndex);
    APPSESSION.lastPluIndex=APPSESSION.currentPluIndex;
    
    [self scrollToCurrentPluIndex];
}

//滚动小类里的tableview
-(void) scrollToCurrentPluIndex{
    DebugLog(@"sectionIndex=%d,pluIndex=%d;pluPlusCount=%d",APPSESSION.currentSortIndex, APPSESSION.currentPluIndex, [APPSESSION.pluPlus count]);
    @try {        
        if (APPSESSION.currentPluIndex <= [APPSESSION.pluPlus count]) {
            NSIndexPath *indexPath=[NSIndexPath indexPathForRow:APPSESSION.currentPluIndex inSection:APPSESSION.currentSortIndex];
            UITableView *atableview=((UITableView *)[self viewWithTag:kTagOfStartTableView]);
            [atableview scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:YES];
        }
        else{
            DebugLog(@"滚动行数越界：sectionIndex=%d,pluIndex=%d;pluPlusCount=%d",APPSESSION.currentSortIndex, APPSESSION.currentPluIndex, [APPSESSION.pluPlus count]);
        }
    }
    @catch (NSException *exception) {
        DebugLog(@"catch:name=%@; reason=%@", [exception name],[exception reason]);
    }
    @finally {
        DebugLog(@"currentPluIndex=%d", APPSESSION.currentPluIndex);
    }
}

#pragma mark -
#pragma mark 重载button处理方法
-(void) buttonClicked:(id)sender{
	NSInteger bid = [sender tag];
    if(bid ==(kTagOfStartBT+0)){//退回到推荐菜界面
        if (APPSESSION.isAnimating) {
            DebugLog(@"动画还未结束...");
            return;
        }
        DebugLog(@"%@", @"退回到推荐菜界面");
        APPSESSION.isViewRemoveFromLef=NO;
        [APPSESSION playSoundOnEvent:[XRmenuPublic getGeneralSkinImg:@"buttonClicked.caf"]];
        [self removeNotification];
        NSDictionary *infos1 = [NSDictionary dictionaryWithObjectsAndKeys:num(ViewOfCommend), @"Step", nil];
        postNWithInfos(kMessage_RootView_ChangeStep, self, infos1);
    }
    else if (bid==(kTagOfStartBT + 1)) {//显示我的点单
        [APPSESSION playSoundOnEvent:[XRmenuPublic getGeneralSkinImg:@"buttonClicked.caf"]];
        postN(kMessage_RootView_MyOrderViewDisplay);
    }
	else if (bid == (kTagOfStartBT + 2)) { //切换显示模式
        if (APPSESSION.isAnimating) {
            DebugLog(@"动画还未结束...");
            return;
        }
        displayIndex++;
        displayIndex=displayIndex % 3;
        DebugLog(@"切换显示模式displayIndex=%d",displayIndex);
        if([self viewWithTag:kTagOfStartMainView+1]){
            DisplayModeView *dmv=(DisplayModeView *)[self viewWithTag:kTagOfStartMainView+1];
            [dmv changeModeView:displayIndex];
            [APPSESSION playSoundOnEvent:[XRmenuPublic getGeneralSkinImg:@"buttonClicked.caf"]];
        }
	}
}

#pragma mark -
#pragma mark Tableview delegate and datasource
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
	return [APPSESSION.pluSorts count];//小类的数量
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{    
    if (section == currentSectionIndex) {
        return [APPSESSION.pluPlus count];//取出当前小类里的菜品数量
    }
    else{
        return 0;
    }
}
//自定义row
-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier1 = @"PluPluCell1";
	MainViewCell *cell = nil;//(MainViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
	if (cell == nil){
		NSString *config = [APPSESSION.allconfig getStringValueAtPath:[NSString stringWithFormat:@"UI Skin/%@/Main View/sub tableview/table cell style", APPSESSION.uistyle]];
		cell = (MainViewCell *)[[[MainViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1 Customer:config] autorelease];
	}
    else{
    }
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    //定义cell里的数据
    [cell setTag:kTagOfTableViewRow+indexPath.row];
    cell.celldata = [APPSESSION.pluPlus objectAtIndex:indexPath.row];
    if (APPSESSION.currentPluIndex == indexPath.row) {//设置当前默认的菜品被选中
        [cell setSelectedRow:YES];
    }else{
        [cell setSelectedRow:NO];
    }
    
    return cell;
}
//自定义section
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    MainViewSection *sectionView = [[MainViewSection alloc] initWithStyle:APPSESSION.uistyle DishSubViewName:@"Main View/Section View"];  
    [sectionView setData:((PluSort *)[APPSESSION.pluSorts objectAtIndex:section]).psDescripts leftOrDown:(section == currentSectionIndex)];
    [sectionView setTag:kTagOfTableViewSection+section];
    sectionView.delegate=self;
	return [sectionView autorelease];
}
//点击小类名称时触发
-(void) sectionHeaderClicked:(MainViewSection *)tapedSection HeadTag:(NSInteger)itag
{
	NSInteger temp = itag-kTagOfTableViewSection;
    [APPSESSION playSoundOnEvent:[XRmenuPublic getGeneralSkinImg:@"trashDish.caf"]];
    [self initMainViewPluSort:temp];
}
//点击菜品触发
- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (APPSESSION.lastPluIndex != indexPath.row) {
        //1.修改当前点中的菜品下标
        [APPSESSION updateCurrentPluIndex:indexPath.row];
        //2.设置当前点中的菜品
        [self SelectMainViewPluPlu];
    }
    //3.更新显示模式界面里的数据
    postN(kMessage_DishplayModeView_UpdateData);
}
- (void)tableView:(UITableView *)aTableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    NSIndexPath *lastIndexPath = [[aTableView indexPathsForVisibleRows] lastObject];    
    if (lastIndexPath.row<([APPSESSION.pluPlus count]-1)) {//设置向下的箭头是否显示
        [self viewWithTag:kTagOfStartBT+5].hidden=NO;
    }
    else{
        [self viewWithTag:kTagOfStartBT+5].hidden=YES;
    }
}
#pragma mark -
//-(void) viewDidUnLoad{
//    DebugLog(@"viewDidUnLoad!!!");
//    [self removeNotification];
//}

//=========================================================== 
// dealloc
//=========================================================== 
- (void)dealloc
{
    DebugLog(@"MainView dealloc!!!");
    [self removeNotification];
    [super dealloc];
} 

@end
